package cn.wh.xwm.controller.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import jxl.read.biff.BiffException;

import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import net.sf.json.JSONObject;
import cn.wh.xwm.common.exception.ExcelException;
import cn.wh.xwm.common.util.BusinessUtil;
import cn.wh.xwm.common.util.Constant;
import cn.wh.xwm.common.util.ExcelParshUtils;
import cn.wh.xwm.common.util.TimeUtils;
import cn.wh.xwm.controller.action.vo.LiquidItem;
import cn.wh.xwm.controller.action.vo.PmView;
import cn.wh.xwm.hibernate.dao.Customerinfo;
import cn.wh.xwm.hibernate.dao.CustomerinfoDAO;
import cn.wh.xwm.hibernate.dao.PmFileUpload;
import cn.wh.xwm.hibernate.dao.PmFileUploadDAO;
import cn.wh.xwm.hibernate.dao.PmLiquidDAO;
import cn.wh.xwm.hibernate.dao.Productinfo;
import cn.wh.xwm.hibernate.dao.ProductinfoDAO;
import cn.wh.xwm.hibernate.dao.Userinfo;

/**
 * PM 管理 ACTION
 * 
 * @author swimming
 * 
 */
@SuppressWarnings("serial")
public class PmAction extends BaseAction {
	private File uploadfile;
	private String uploadfileContentType;
	private String uploadfileFileName;
	private String id;
	private String customerid;
	private String liquiddate;
	private String page;
	private String rows;

	public File getUploadfile() {
		return uploadfile;
	}

	public void setUploadfile(File uploadfile) {
		this.uploadfile = uploadfile;
	}

	/**
	 * 查询所有文件
	 * 
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public void findAlluploadfile() throws IOException {
		Userinfo userinfo = this.getUserinfoFromSession();
		PmFileUploadDAO dao = new PmFileUploadDAO();
		List<PmFileUpload> list = dao.findBypage(page, rows, "PmFileUpload",
				userinfo.getUserid());
		List<PmView> vlist = new ArrayList<PmView>();
		for (PmFileUpload upload : list) {
			PmView view = new PmView();
			view.setId(upload.getId());
			view.setCustomerlevel(upload.getCustomerinfo().getLevel());
			view.setCustomername(upload.getCustomerinfo().getName());
			view.setCustomerid(upload.getCustomerinfo().getId());
			view.setUploadfilename(upload.getFileName());
			view.setActiondate(TimeUtils.toIsoDate(upload.getLiquidDate()));
			vlist.add(view);
		}
		JSONObject object = new JSONObject();
		object.put("rows", vlist);
		object.put("total", dao.findTotalCount("PmFileUpload"));
		dao.getSession().close();
		this.responseJson(object);
	}

	/**
	 * 删除上传文件
	 * 
	 * @throws IOException
	 * @throws ExcelException
	 * @throws BiffException
	 * @throws IOException 
	 */
	public void deleteFile() throws BiffException, IOException {
		String separator = System.getProperty("file.separator");
		PmFileUploadDAO dao = new PmFileUploadDAO();
		PmFileUpload fileUpload = dao.findById(id);
		String filename = fileUpload.getFileName();
		Transaction ts = dao.getSession().getTransaction();
		ts.begin();
		dao.delete(fileUpload);
		ts.commit();
		File f = new File(this.getServerPath() + "uploadfiles" + separator
				+ filename);
		try {
			this.deleteRelatedRecord(f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		f.delete();
		JSONObject object = new JSONObject();
		object.put("success", true);
		dao.getSession().close();
		this.responseJson(object);
	}

	/**
	 * 删除该文件相关的数据记录
	 * 
	 * @param f
	 * @throws IOException
	 * @throws BiffException
	 */
	private void deleteRelatedRecord(File f) throws BiffException, IOException {
		HashMap<String, ArrayList<LiquidItem>> map = ExcelParshUtils.instance()
				.getLiquiidsFromFile(f);
		for (int i = 0; i < 6; i++) {
			String productName = BusinessUtil.getKey(i);
			ProductinfoDAO pdao = new ProductinfoDAO();
			String productId = ((Productinfo) (pdao.findByName(productName)
					.get(0))).getId();
			ArrayList<LiquidItem> list = map.get(productName);
			if (list.size() > 0) {
				PmLiquidDAO dao = new PmLiquidDAO();
				Transaction ts = dao.getSession().getTransaction();
				ts.begin();
				dao.delete(list, f.getName(), productId, customerid);
				ts.commit();
			}
		}
		System.out.println("parseExcel" + map);

	}

	/**
	 * 上传文件
	 * 
	 * @throws IOException
	 * 
	 * @throws IOException
	 * @throws BiffException
	 * @throws BiffException
	 * @throws ParseException 
	 * @throws HibernateException 
	 */
	public void uploadfile() throws IOException, BiffException, ParseException, HibernateException {
			JSONObject object = new JSONObject();
			if(ExcelParshUtils.instance().validateFile(uploadfile)){
				Userinfo userinfo = this.getUserinfoFromSession();
				PmFileUpload fileUpload = new PmFileUpload();
				CustomerinfoDAO cdao = new CustomerinfoDAO();
				Customerinfo cinfo = cdao.findById(customerid);
				fileUpload.setCustomerinfo(cinfo);
				fileUpload.setFileName(uploadfile.getName().replaceAll(".tmp",
				".xls"));
				fileUpload.setLiquidDate(TimeUtils.fromIsoDate(liquiddate));
				fileUpload.setUserId(userinfo.getUserid());
				PmFileUploadDAO dao = new PmFileUploadDAO();
				dao.getSession().beginTransaction();
				dao.save(fileUpload);
				this.saveFileToDisk(uploadfile);
				this.parseFile(uploadfile);
				dao.getSession().getTransaction().commit();
				dao.getSession().close();
				object.put("success", true);
				this.responseJson(object);
			}else{
				object.put("errorMsg", "请检查上传的EXCEL文件格式是否正确");
				this.responseJson(object);
			}
	}

	private boolean validate(HashMap<String, ArrayList<LiquidItem>> map) {
		Set<String> keys = map.keySet();
		for (String key : keys) {
			ArrayList<LiquidItem> list = map.get(key);
			for (LiquidItem item : list) {
				item.getAmount();
				item.getCustomerName();
				item.getEventDate();
			}
		}
		return false;
	}

	/**
	 * 存文件到数据库
	 * 
	 * @param uploadfile2
	 * @throws IOException
	 * @throws BiffException
	 */
	private void parseFile(File uploadfile2) throws BiffException, IOException {
		HashMap<String, ArrayList<LiquidItem>> map = ExcelParshUtils.instance()
				.getLiquiidsFromFile(uploadfile);
		String filename = uploadfile2.getName().replaceAll(".tmp", ".xls");
		for (int i = 0; i < 6; i++) {
			String productName = BusinessUtil.getKey(i);
			ProductinfoDAO pdao = new ProductinfoDAO();
			String productId = ((Productinfo) (pdao.findByName(productName)
					.get(0))).getId();
			ArrayList<LiquidItem> list = map.get(productName);
			if (list.size() > 0) {
				PmLiquidDAO dao = new PmLiquidDAO();
				dao.save(list, filename, productId, customerid);
			}
		}

		System.out.println("parseExcel" + map);

	}

	/**
	 * 保存文件
	 * 
	 * @param source
	 */
	private void saveFileToDisk(File source) {
		try {
			FileInputStream fis = new FileInputStream(source);
			String separator = System.getProperty("file.separator");
			String filename = source.getName().replaceAll(".tmp", ".xls");
			FileOutputStream fos = new FileOutputStream(this.getServerPath()
					+ "uploadfiles" + separator + filename);
			int readbyte;
			while ((readbyte = fis.read()) != -1) {
				fos.write((char) readbyte);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getUploadfileContentType() {
		return uploadfileContentType;
	}

	public void setUploadfileContentType(String uploadfileContentType) {
		this.uploadfileContentType = uploadfileContentType;
	}

	public String getUploadfileFileName() {
		return uploadfileFileName;
	}

	public void setUploadfileFileName(String uploadfileFileName) {
		this.uploadfileFileName = uploadfileFileName;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCustomerid() {
		return customerid;
	}

	public void setCustomerid(String customerid) {
		this.customerid = customerid;
	}

	public String getLiquiddate() {
		return liquiddate;
	}

	public void setLiquiddate(String liquiddate) {
		this.liquiddate = liquiddate;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

}
